<?php

namespace App\Admin\Controllers;

use App\Helpers\Helpers;
use App\Model\Category;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Validation\Rule;

class CategoryController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '商品分类';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Category);

        $grid->column('id', __('Id'));
        $grid->column('name', __('分类名'));
        $grid->column('sort', __('Sort'));
        $grid->column('is_show', __('Is show'))->display(function ($data) {
            return $data ? '显示' : '隐藏';
        });
        $grid->column('created_at', __('Created at'));

        $grid->filter(function (/** @var Grid\Filter $filter */ $filter) {
            $filter->disableIdFilter();
            // 在这里添加字段过滤器
            $filter->like('name', '分类名');
        });


        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Category::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('name', __('分类名'));
        $show->field('sort', __('Sort'));
        $show->field('is_show', __('Is show'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Category);

        $params = request()->route()->parameters();

        if (isset($params['category'])) {
            $id = ['category'];
        } else {
            $id = 0;
        }
        $form->text('name', __('分类名'))
            ->creationRules([
                'required',
//                Rule::unique('category', 'name')->whereNull('deleted_at')
            ])
            ->updateRules([
                'required',
//                Rule::unique('category', 'name')->whereNull('deleted_at')->ignore($id)
            ])
            ->required();
        $form->number('sort', __('Sort'))
            ->rules('integer')
            ->default(0);
        $form->switch('is_show', __('Is show'))->default(true);

        $form->image('thumb', __('Category thumb'))->uniqueName();

        return $form;
    }
}
